package com.ruoyi.report.service.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.YesNoLabelEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.report.domain.HeatSource;
import com.ruoyi.report.domain.PlatformToken;
import com.ruoyi.report.mapper.HeatSourceMapper;
import com.ruoyi.report.service.IHeatSourceService;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author lisongtao
 * @date 2023/10/19 11:23
 */
@Service("heatSourceService")
public class HeatSourceServiceImpl implements IHeatSourceService {

    private static final Logger logger = LoggerFactory.getLogger(HeatSourceServiceImpl.class);

    /**
     * 热力上传token
     */
    private static final String HEAT_SOURCE_TOKEN_KEY = "heat:source:token";

    @Autowired
    private HeatSourceMapper heatSourceMapper;
    @Autowired
    public RedisCache redisCache;
    @Autowired
    public ISysConfigService sysConfigService;


    /**
     * 上报供热数据
     */
    @Override
    public void reportHeatingData() {
        logger.error("开始查询上报数据 " + DateUtils.dateTimeNow());
        HeatSource latestRecord = heatSourceMapper.getLatestRecord();
        if (latestRecord == null) {
            logger.error("查询数据失败 获取数据为空 " + DateUtils.dateTimeNow());
            return;
        }
        String uploadState = latestRecord.getUploadState();
        if (YesNoLabelEnum.Y.name().equals(uploadState)) {
            logger.error("当前数据已上报不需要再次上报 " + (latestRecord.getInDateTime() != null ? DateUtils.dateTime2(latestRecord.getInDateTime()) : "") + "  "
                    + latestRecord.getUploadState() + " " + (latestRecord.getUploadTime() != null ? DateUtils.dateTime2(latestRecord.getUploadTime()) : ""));
            return;
        }
        String accessToken = getAccessToken();
        String uploadUrl = sysConfigService.selectConfigByKey("heat.upload.url");
        String companyName = sysConfigService.selectConfigByKey("heat.upload.companyName");
        String heatName = sysConfigService.selectConfigByKey("heat.upload.heatName");
        String requestType = sysConfigService.selectConfigByKey("heat.upload.requestType");
        String requestId = sysConfigService.selectConfigByKey("heat.upload.requestID");

        JSONObject heatUploadInParameter = new JSONObject();
//        try {
//            heatUploadInParameter.put("CompanyName", URLEncoder.encode(companyName, StandardCharsets.UTF_8.name()));
//            heatUploadInParameter.put("HeatName", URLEncoder.encode(heatName, StandardCharsets.UTF_8.name()));
//        } catch (UnsupportedEncodingException e) {
//            throw new ServiceException("汉字编码失败！");
//        }
        heatUploadInParameter.put("DateTime", DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        heatUploadInParameter.put("PrimaryFeedTem", latestRecord.getPrimaryFeedTem() == null ? "" : latestRecord.getPrimaryFeedTem().toString());
        heatUploadInParameter.put("PrimaryFeedPressure", latestRecord.getPrimaryFeedPressure() == null ? "" : latestRecord.getPrimaryFeedPressure().toString());
        heatUploadInParameter.put("PrimaryReturnTem", latestRecord.getPrimaryReturnTem() == null ? "" : latestRecord.getPrimaryReturnTem().toString());
        heatUploadInParameter.put("PrimaryReturnPressure", latestRecord.getPrimaryReturnPressure() == null ? "" : latestRecord.getPrimaryReturnPressure().toString());
        heatUploadInParameter.put("FeedFlow", latestRecord.getFeedFlow() == null ? "" : latestRecord.getFeedFlow().toString());
        heatUploadInParameter.put("ReturnFlow", latestRecord.getReturnFlow() == null ? "" : latestRecord.getReturnFlow().toString());
        heatUploadInParameter.put("CompanyName", companyName);
        heatUploadInParameter.put("HeatName", heatName);
        JSONObject heatUploadParameter = new JSONObject();
        heatUploadParameter.put("InParam", heatUploadInParameter);
        heatUploadParameter.put("RequestType", requestType);
        heatUploadParameter.put("RequestID", requestId);

        // 转为map
        logger.error("访问的数据为 url " + uploadUrl + " param :" + heatUploadParameter + " headers: Bearer " + accessToken);
        String params = heatUploadParameter.toJSONString();
        String responseData = HttpRequest.post(uploadUrl).header("Authorization", "Bearer " + accessToken).body(params).timeout(10 * 1000).execute().body();
        if (StringUtils.isBlank(responseData)) {
            logger.error("上传接口报错  访问的数据为 url " + uploadUrl + " param :" + heatUploadParameter + " headers: Bearer " + accessToken + " 返回值：" + responseData);
            return;
        }
        JSONObject jsonObject1 = JSON.parseObject(responseData);
        String status = jsonObject1.getString("status");
        if (String.valueOf(HttpStatus.SUCCESS).equals(status)) {
            // 数据成功上传，会写成功标识
            latestRecord.setRequestData(params);
            latestRecord.setResponseData(responseData);
            latestRecord.setUploadTime(new Date());
            latestRecord.setUploadState(YesNoLabelEnum.Y.name());
            int num = heatSourceMapper.updateLatestRecord(latestRecord);
            if (num > 0) {
                logger.error("上传接口成功  访问的数据为 url " + uploadUrl + " param :" + heatUploadParameter + " headers: Bearer " + accessToken + " 返回值：" + responseData + " num:" + num);
            } else {
                logger.error("上传接口报错  访问的数据为 url " + uploadUrl + " param :" + heatUploadParameter + " headers: Bearer " + accessToken + " 返回值：" + responseData + " num:" + num);
            }
        } else {
            logger.error("上传接口报错  访问的数据为 url " + uploadUrl + " param :" + heatUploadParameter + " headers: Bearer " + accessToken + " 返回值：" + responseData);
        }
    }

    @Override
    public synchronized String getAccessToken() {
        // 初次进入先在redis中获取accessToken值
        String accessToken = redisCache.getCacheObject(HEAT_SOURCE_TOKEN_KEY);
        if (StringUtils.isNotBlank(accessToken)) {
            return accessToken;
        }
        String url = sysConfigService.selectConfigByKey("heat.token.url");
        String password = sysConfigService.selectConfigByKey("heat.token.password");
        String client_id = sysConfigService.selectConfigByKey("heat.token.client_id");
        String client_secret = sysConfigService.selectConfigByKey("heat.token.client_secret");
        String username = sysConfigService.selectConfigByKey("heat.token.username");
        String redirect_uri = sysConfigService.selectConfigByKey("heat.token.redirect_uri");
        String grantType = sysConfigService.selectConfigByKey("heat.token.grantType");
        logger.error("访问url " + url + " 访问参数:" + password + "  " + client_id + "  " + client_secret + "  " + username + "  " + redirect_uri + "  " + grantType);
        String formData = null;
        try {
            formData = "grant_type=" + URLEncoder.encode(grantType, StandardCharsets.UTF_8.name())
                    + "&client_id=" + URLEncoder.encode(client_id, StandardCharsets.UTF_8.name())
                    + "&client_secret=" + URLEncoder.encode(client_secret, StandardCharsets.UTF_8.name())
                    + "&username=" + URLEncoder.encode(username, StandardCharsets.UTF_8.name())
                    + "&password=" + URLEncoder.encode(password, StandardCharsets.UTF_8.name())
                    + "&redirect_uri=" + URLEncoder.encode(redirect_uri, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("访问url " + url + " 访问参数:" + password + "  " + client_id + "  " + client_secret + "  " + username + "  " + redirect_uri + "  " + grantType + " url 编码失败 ");
            throw new ServiceException(e.getMessage());
        }
        logger.error("url " + url + " 参数：" + formData);
        String responseBody = HttpUtils.postWithParamsForString(url, formData);
        if (StringUtils.isBlank(responseBody)) {
            throw new ServiceException("访问平台获取token失败！");
        }
        PlatformToken platformToken = JSON.parseObject(responseBody, PlatformToken.class);
        if (platformToken == null || StringUtils.isBlank(platformToken.getAccess_token())) {
            throw new ServiceException("访问平台获取token失败2！");
        }
        // 成功获取token，将token放入到redis中
        accessToken = platformToken.getAccess_token();
        redisCache.setCacheObject(HEAT_SOURCE_TOKEN_KEY, accessToken, 3000, TimeUnit.SECONDS);
        return accessToken;
    }

}
